package org.finalministry.database.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class FinalministryDatabaseConnection implements IDatabaseConnection {

	private Connection conn;

	private String databaseName;
	private String username;
	private String password;
	private int port;

	public FinalministryDatabaseConnection(String databaseName, String username, String password, int port) throws ClassNotFoundException,
			SQLException {
		this.databaseName = databaseName;
		this.username = username;
		this.password = password;
		this.port = port;
		connect(databaseName, username, password, port);
	}

	private void connect(String databaseName, String username, String password, int port) throws ClassNotFoundException, SQLException {
		Class.forName("org.h2.Driver");
		conn = DriverManager.getConnection("jdbc:h2:~/" + databaseName, username, password);
		conn.setAutoCommit(true);
	}

	@Override
	public Connection getConnection() throws ClassNotFoundException, SQLException {

		if (conn == null) {
			connect(databaseName, username, password, port);
		}

		// reconnect if connection is closed
		if (conn.isClosed()) {
			System.out.println("Reconnect to database");
			connect(databaseName, username, password, port);
		}

		return conn;
	}

	@Override
	public void closeConnection() throws SQLException {

		System.out.println("Try to close connection");

		if (conn != null) {
			conn.close();
			System.out.println("Connection closed");
		}
	}

	@Override
	public boolean isConnectionActive() throws SQLException {

		if (conn == null) {
			return false;
		}

		return !conn.isClosed();
	}

	public String getDatabaseName() {
		return databaseName;
	}

	public void setDatabaseName(String databaseName) {
		this.databaseName = databaseName;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

}
